package com.adds.lvds.security.controller;

/**
 * 武汉天瑞兴科技有限公司
 */
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.adds.lvds.core.utils.CommUtils;
import com.adds.lvds.core.utils.Md5Tool;
import com.adds.lvds.model.organize.SysUserInfo;
import com.adds.lvds.model.organize.SysUserPermission;
import com.adds.lvds.security.BaseController;
import com.adds.lvds.security.acegi.utils.CurrentUserUtils;
import com.adds.lvds.security.model.SysCurrentUser;
import com.adds.lvds.security.model.SysRole;
import com.adds.lvds.security.model.SysRoleUser;
import com.adds.lvds.security.service.SysRoleService;
import com.adds.lvds.security.service.SysUserService;
import com.adds.lvds.service.impl.organize.SysUserInfoService;

/**
 * 
 * 项目名称 ：lvds-web-controller <code>用户管理业务层</code>
 * 
 * @author zhangjian
 * @time 2017-1-11下午4:02:14
 */
@Controller
@RequestMapping("/security/user/")
public class SysUserController extends BaseController<SysCurrentUser> {

	@Inject
	private SysUserService sysUserService;

	@Inject
	private SysRoleService roleService;

	@Inject
	private SysUserInfoService sysUserInfoService;

	@RequestMapping("sys_user_list")
	public String sys_user_list(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取当前用户名称是否为admin超级用户
		SysCurrentUser sysCurrentUser = CurrentUserUtils.currentUser(request);
		String userName = sysCurrentUser.getUserName();
		model.addAttribute("userName", userName);
		SysRole role = sysCurrentUser.getRoleList().get(0);
		List<SysRole> roleList = null;
		map.clear();
		switch (role.getRole_level()) {
		case 0:
			roleList = roleService.querySysRoleByMap(map);
			break;
		case 1:
			map.put("level", 2);
			roleList = roleService.querySysRoleByMap(map);
			break;
		case 3:
			map.put("level", 4);
			roleList = roleService.querySysRoleByMap(map);
			break;
		}
		model.addAttribute("roleList", roleList);
		return "/security/user/sys_user_list";
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @param resources
	 *            获取查询条件
	 * @param page
	 *            获取当前页数,page是jqGrid自带参数
	 * @param rows
	 *            获取每页显示行数,rows是jqGrid自带参数
	 * @param sidx
	 *            获取排序列名,sidx是jqGrid自带参数
	 * @param sord
	 *            获取排序方式,sord是jqGrid自带参数
	 */
	@ResponseBody
	@RequestMapping(value = "loadDataGrid")
	public Map<String, Object> loadDataGrid(HttpServletRequest request,
			HttpServletResponse response,
			@Param(value = "currentUser") SysCurrentUser currentUser,
			@Param(value = "page") String page,
			@Param(value = "rows") String rows,
			@Param(value = "sidx") String sidx,
			@Param(value = "sord") String sord) {
		// 将当前操作员id赋值给条件中的操作员
		if (!StringUtils.equals(CurrentUserUtils.currentUser(request)
				.getUserName(), "admin")) {
			currentUser.setId(CurrentUserUtils.currentUser(request).getId());
		}
		pageView = sysUserService.query(getPageView(page, rows, sidx, sord),
				currentUser);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", pageView.getRecords());
		map.put("records", pageView.getRowCount());
		map.put("page", pageView.getPageNow());
		map.put("total", pageView.getPageCount());
		return map;
	}

	/**
	 * 加载新增界面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("addSysUser")
	public String addSysUser(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		return "/security/user/add_sys_user";
	}

	/**
	 * 执行新增
	 * 
	 * @param model
	 * @param videoType
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "doAddSysUser")
	public Map<String, Object> doAddSysUser(
			@Param("sysUser") SysCurrentUser sysUser,
			@Param("sysUserPermission") SysUserPermission sysUserPermission,
			@Param("sysRoleUser") SysRoleUser sysRoleUser,
			@Param("sysUserInfo") SysUserInfo sysUserInfo, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		sysUser.setState(1);
		sysUser.setPassword(Md5Tool.getMd5(sysUser.getPassword()));
		SysCurrentUser user = CurrentUserUtils.currentUser(request);
		sysUser.setOperator(user.getId());
		String result = sysUserService.addSysUser(sysUser, sysUserInfo,
				sysRoleUser,sysUserPermission);

		String msg = "";
		switch (result) {
		case CommUtils.SUCC:
			msg = "录入用户数据成功！";
			break;
		case CommUtils.ERROR:
			msg = "录入用户数据失败！";
			break;
		}
		map.put("errcode", result);
		map.put("errmsg", msg);
		return map;
	}

	/**
	 * 修改页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("editSysUser")
	public String editSysUser(HttpServletRequest request, Model model,
			@Param("userId") String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", userId);
		// 获取当前用户信息
		SysCurrentUser sysUser = sysUserService.getSysUserByMap(map);
		model.addAttribute("sysUser", sysUser);
		// 获取角色
		SysCurrentUser sysCurrentUser = CurrentUserUtils.currentUser(request);
		SysRole role = sysCurrentUser.getRoleList().get(0);
		List<SysRole> roleList = null;
		map.clear();
		switch (role.getRole_level()) {
		case 0:
			roleList = roleService.querySysRoleByMap(map);
			break;
		case 1:
			map.put("level", 2);
			roleList = roleService.querySysRoleByMap(map);
			break;
		case 3:
			map.put("level", 4);
			roleList = roleService.querySysRoleByMap(map);
			break;
		}
		model.addAttribute("roleList", roleList);
		List<SysRole> userRole = sysUser.getRoleList();
		Integer roleId = 0;
		if (userRole != null && userRole.size() > 0) {
			roleId = userRole.get(0).getId();
		}
		model.addAttribute("roleId", roleId);
		return "/security/user/edit_sys_user";
	}

	/**
	 * 编辑用户信息
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("doEditSysUser")
	public Map<String, Object> doEditSysUser(Model model,
			@Param("sysUser") SysCurrentUser sysUser,
			@Param("sysUserPermission") SysUserPermission sysUserPermission,
			@Param("sysRoleUser") SysRoleUser sysRoleUser,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String result = sysUserService.updateSysUser(sysUser, sysRoleUser,sysUserPermission);
		String msg = "";
		switch (result) {
		case CommUtils.SUCC:
			msg = "编辑用户数据成功！";
			break;
		case CommUtils.ERROR:
			msg = "编辑用户数据失败！";
			break;
		}
		map.put("errcode", result);
		map.put("errmsg", msg);
		return map;
	}

	/**
	 * 接收用户名和角色名
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("role_sys_user")
	public String userRoleSysUser(Model model, String userName, String roleName) {

		try {
			userName = java.net.URLDecoder.decode(userName, "UTF-8");
			roleName = java.net.URLDecoder.decode(roleName, "UTF-8");
		} catch (UnsupportedEncodingException e) {

		}
		model.addAttribute("userName", userName);
		model.addAttribute("roleName", roleName);

		return "/user/role_sys_user";
	}

	/**
	 * 验证账号是否存在
	 * 
	 * @author
	 * @param name
	 * @return
	 */
	@RequestMapping("checkSysUser")
	@ResponseBody
	public boolean checkSysUser(@Param("userName") String userName) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", userName);
		SysCurrentUser sysUser = sysUserService.getSysUserByMap(map);
		if (sysUser == null) {
			return true;// 不存在相同的返回true
		} else {
			return false;// 存在相同的返回false
		}
	}

	/**
	 * 通过Id删除记录
	 * 
	 * @param model
	 * @param videoTypeId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("deleteSysUser")
	public Map<String, Object> deleteSysUser(Model model,
			@Param("id") String[] ids) {
		Map<String, Object> map = new HashMap<String, Object>();
		String result = sysUserService.deleteSysUser(ids);
		String msg = "";
		switch (result) {
		case CommUtils.SUCC:
			msg = "批量删除用户数据成功！";
			break;
		case CommUtils.ERROR:
			msg = "批量删除用户数据失败！";
			break;
		}
		map.put("errcode", result);
		map.put("errmsg", msg);
		return map;
	}

	/**
	 * 禁用与启用
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("disableSysUser")
	public Map<String, Object> disableSysUser(HttpServletRequest request,
			@Param("id") Integer id, @Param("state") Integer state) {
		Map<String, Object> map = new HashMap<String, Object>();
		String result = CommUtils.SUCC;
		SysCurrentUser sysUser = new SysCurrentUser();
		sysUser.setId(id);
		sysUser.setState(state);
		result = sysUserService.editSysUserByMap(sysUser);
		String msg = "";
		switch (result) {
		case CommUtils.SUCC:
			msg = "账户状态设置成功！";
			break;
		case CommUtils.ERROR:
			msg = "账户状态设置失败！";
			break;
		}
		map.put("errcode", result);
		map.put("errmsg", msg);
		return map;
	}

	/**
	 * 加载分配权限界面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("editUserRole")
	public String showUserRole(@RequestParam String user_id,
			HttpServletRequest request) {
		request.setAttribute("userRoleList",
				roleService.findSysUserRoleByUserId(user_id));
		request.setAttribute("noUserRoleList",
				roleService.findNoSysUserRoleByUserId(user_id));
		// 遍历已有角色权限id，通过；分号分割拼接 role_ids
		List<SysRole> list = roleService.findSysUserRoleByUserId(user_id);
		String role_ids = "";
		for (SysRole sysRole : list) {
			if (role_ids.equals("")) {
				role_ids = String.valueOf(sysRole.getId());
			} else {
				role_ids = role_ids + ";" + String.valueOf(sysRole.getId());
			}
		}
		request.setAttribute("role_ids", role_ids);
		request.setAttribute("user_id", user_id);
		return "/security/user/edit_user_role";
	}

	/**
	 * 通过Id获取已分配权限
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("doUserRole")
	public Integer doUserRole(HttpServletRequest request) {
		Integer flag = 1;
		try {
			List<String> list = new ArrayList<>();
			String user_id = request.getParameter("user_id");
			String roleId = request.getParameter("role_ids");
			String[] roles = roleId.split(";");
			for (String role_id : roles) {
				if (role_id != null && !"".equals(role_id)) {
					list.add(role_id);
				}
			}
			roleService.addUserRole(user_id, list);
			flag = 0;
		} catch (Exception e) {
			flag = 1;
		}
		return flag;
	}// 需求能否通过一个方法名传递两个方法的值1，用if语句进行判断，2用map传送两个被包含的map

	/**
	 * 修改头像
	 * 
	 * @param request
	 *            找到当前用户session
	 * @param multipart
	 *            文件
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("editHeadImg")
	@ResponseBody
	public Map<String, Object> editHeadImg(HttpServletRequest request,
			@RequestParam(value = "image_file") MultipartFile multipart) {
		Map<String, Object> map = new HashMap<>();
		String result = CommUtils.SUCC;
		String root = request.getSession().getServletContext()
				.getRealPath("/upload/uploadImg");
		if (!multipart.isEmpty()) {
			String prefix = FilenameUtils.getExtension(multipart
					.getOriginalFilename());// 原文件后缀

			SysCurrentUser currentUser = CurrentUserUtils.currentUser(request);
			String fileName = System.currentTimeMillis() + "." + prefix;
			File file = new File(root + File.separator + fileName);
			try {
				FileUtils.copyInputStreamToFile(multipart.getInputStream(),
						file);
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 图片根路径
			fileName = "/upload/uploadImg/" + fileName;
			SysCurrentUser user = new SysCurrentUser();
			user.setHead_img(fileName);
			user.setId(currentUser.getId());
			// 执行修改操作
			result = sysUserService.editSysUserByMap(user);
		}
		String msg = "";
		switch (result) {
		case CommUtils.SUCC:
			msg = "设置头像成功！";
			break;
		case CommUtils.ERROR:
			msg = "设置头像失败，请重新设置！";
			break;
		}
		map.put("errcode", result);
		map.put("errmsg", msg);
		return map;
	}

	/**
	 * 密码校验
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "checkPaswd")
	@ResponseBody
	public Map<String, Object> checkPaswd(HttpServletRequest request,
			@Param("user_id") String user_id,
			@Param("oldpassword") String oldpassword) {
		String result = CommUtils.SUCC;
		Map<String, Object> map = new HashMap<>();
		map.put("id", user_id);
		SysCurrentUser currentUser = sysUserService.getSysUserByMap(map);
		if (!currentUser.getPassword().equals(Md5Tool.getMd5(oldpassword))) {
			result = CommUtils.ERROR;
		}
		String msg = "";
		switch (result) {
		case CommUtils.SUCC:
			msg = "密码正确！";
			break;
		case CommUtils.ERROR:
			msg = "密码错误，请重新输入！";
			break;
		}
		map.put("errcode", result);
		map.put("errmsg", msg);
		return map;
	}

	/**
	 * 重置密码
	 */
	@RequestMapping("resetPwd")
	@ResponseBody
	public Map<String, Object> resetPwd(HttpServletRequest request,
			@Param("userId") Integer userId,
			@Param("newpassword") String newpassword) {
		Map<String, Object> map = new HashMap<String, Object>();
		SysCurrentUser sysUser = new SysCurrentUser();
		sysUser.setId(userId);
		sysUser.setPassword(Md5Tool.getMd5(newpassword));
		String result = sysUserService.editSysUserByMap(sysUser);
		String msg = "";
		switch (result) {
		case CommUtils.SUCC:
			msg = "修改密码成功！";
			break;
		case CommUtils.ERROR:
			msg = "修改密码失败，请重新输入！";
			break;
		}
		map.put("errcode", result);
		map.put("errmsg", msg);
		return map;
	}

	@RequestMapping("checkEmpid")
	@ResponseBody
	public Map<String, Object> checkEmpid(@Param("emp_id")String emp_id) {
		Map<String, Object> map = new HashMap<>();
		// 查询员工是否存在
		SysUserInfo sysInfo = sysUserInfoService.getByInfoId(emp_id);
		if (StringUtils.isEmpty(sysInfo.getUser_id()+"")) {
			map.put("result", "2"); // 当前员工不存在
		} else {
			map.put("emp_id", emp_id);
			map.put("user_id", "0");
			SysUserInfo sysInfo2 = sysUserInfoService
					.querySysUserInfoByMap(map);
			if (sysInfo2 == null) {
				map.put("result", "1"); // 当前员工已经开户
			} else {
				map.put("result", "0");// 当前员工为可以开户
				map.put("sysUserInfo", sysInfo2);
			}
		}
		return map;
	}

}